package com.aube.plugin.previous;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aube.plugin.draw.FixedSizeImageView;
import com.aube.plugin.origin.R;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.dynamicload.DLLayout;
import com.huyn.baseframework.dynamicload.IPositionManager;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.CategorySimple;
import com.huyn.baseframework.utils.StringUtils;
import com.ryg.dynamicload.internal.DLIntent;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 17/1/22.
 */
public class WidgetPrevious extends DLLayout {

    private IPositionManager mManager;

    private LinearLayout mLayoutGroup;
    private AtomicBoolean mAnimated = new AtomicBoolean(false);
    private View mFlag, mHeadLayout;
    private TextView mMore, mTitle;
    private ImageView mArrow;

    private FixedSizeImageView mImg;

    private CategorySimple mCate;

    public WidgetPrevious(Context context) {
        this(context, null);
    }

    public WidgetPrevious(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WidgetPrevious(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void initViews() {
        LayoutInflater.from(context).inflate(R.layout.widget_previous, this, true);
        mLayoutGroup = (LinearLayout) findViewById(R.id.draw_widget_group);

        mFlag = findViewById(R.id.header_flag);
        mTitle = (TextView) findViewById(R.id.header_widget_title);
        mMore = (TextView) findViewById(R.id.header_widget_more);
        mHeadLayout = findViewById(R.id.header_widget_layout);

        mArrow = (ImageView) findViewById(R.id.header_widget_arrow);

        mFlag.setAlpha(0f);
        mTitle.setAlpha(0f);
        mMore.setAlpha(0f);
        mArrow.setAlpha(0f);
    }

    @Override
    public void fillData(Object object) {
        if(object == null || !(object instanceof Category))
            return;
        final Category category = (Category) object;
        mCate = category.getSimpleCategory();

        mTitle.setText(category.modelName);
        if(StringUtils.isNotBlank(category.modelDesc)) {
            mMore.setText(category.modelDesc);
            mHeadLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            });
        } else {
            mMore.setVisibility(View.GONE);
            mArrow.setVisibility(View.GONE);
        }

        List list = (List) category.dataDetail;
        try {
            PreviousModel item = getModel(list);
            final String templateCode = (String) category.getStrFromExtra("templateCode");
            if (item != null) {
                if (StringUtils.isNotBlank(item.picUrl)) {
                    mImg = new FixedSizeImageView(getContext());
                    mImg.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    mLayoutGroup.addView(mImg, params);
                    mImg.updateSize(item.width, item.height);
                    ImageLoader.getInstance(getContext()).fillImage(mImg, item.picUrl);

                    mImg.setAlpha(0f);
                }

                mImg.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //do jump
                        if(mBridge != null) {
                            DLIntent intent = new DLIntent("com.aube.plugin.origin", "com.aube.plugin.previous.PreviousActivity");
                            intent.putExtra(PreviousActivity.CODE, templateCode);
                            intent.putExtra(PreviousActivity.TITLE, category.modelName);
                            mBridge.openPluginActivity(intent);
                        }
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private PreviousModel getModel(List list) {
        for(Object obj : list) {
            PreviousModel item = new PreviousModel();

            LinkedHashMap<String, Object> lhm = (LinkedHashMap<String, Object>) obj;
            Iterator<String> keyIterator = lhm.keySet().iterator();
            while (keyIterator.hasNext()) {
                String key = keyIterator.next();
                Object value = lhm.get(key);

                item.setItem(key, value);
            }
            return item;
        }
        return null;
        //test
//        PreviousModel item = new PreviousModel();
//        item.picUrl = "http://static02.aube-tv.com/upload/images/stagePhoto/201608/s_3ec29faf_1568cb5519a__7f5f.jpg";
//        item.width = 800;
//        item.height = 300;
//        return item;
    }

    private void showHeader(int animDelay) {
        ObjectAnimator alphaTitle = ObjectAnimator.ofFloat(mTitle, "alpha", 0, 1);
        alphaTitle.setDuration(300);
        if(animDelay > 0)
            alphaTitle.setStartDelay(animDelay);

        ObjectAnimator alphaDes = ObjectAnimator.ofFloat(mMore, "alpha", 0, 1);
        alphaDes.setDuration(300);
        alphaDes.setStartDelay(400 + animDelay);

        ObjectAnimator alphaArrow = ObjectAnimator.ofFloat(mArrow, "alpha", 0, 1);
        alphaArrow.setDuration(300);
        alphaArrow.setStartDelay(400 + animDelay);

        ObjectAnimator translate = ObjectAnimator.ofFloat(mFlag, "translationY", -mFlag.getHeight(), 0);
        translate.setDuration(300);
        translate.setStartDelay(800 + animDelay);
        translate.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mFlag.setAlpha(1f);
            }
        });

        AnimatorSet mSet = new AnimatorSet();
        mSet.playTogether(alphaTitle, alphaDes, alphaArrow, translate);
        mSet.start();
    }

    private void animImgAndtip(int delay) {
        if(mImg != null) {
            ValueAnimator imgAnim = ValueAnimator.ofFloat(0, 1);
            imgAnim.setDuration(300);
            imgAnim.setStartDelay(delay);
            imgAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                    mImg.setAlpha(value);
                }
            });
            imgAnim.start();
        }
    }

    @Override
    public void notifyAnim(int animDelay) {
        if(mManager == null)
            return;
        if(mAnimated.get())
            return;
        mAnimated.set(true);
        mLayoutGroup.setVisibility(View.VISIBLE);
        showHeader(animDelay);
        animImgAndtip(animDelay + 400);
    }

    @Override
    public void registToManager(IPositionManager manager) {
        if(mManager != null || manager == null)
            return;
        manager.add(this);
        this.mManager = manager;

        mLayoutGroup.setVisibility(View.INVISIBLE);
    }

    @Override
    public void unreistFromManager(IPositionManager manager) {
        if(mManager == null || manager == null)
            return;
        manager.remove(this);
        this.mManager = null;
    }

    @Override
    public int[] getLocations() {
        int[] locs = new int[2];
        getLocationOnScreen(locs);
        return locs;
    }

    @Override
    public void setTheme(int themeColor) {
        mFlag.setBackgroundColor(themeColor);
    }
}
